import { AssertionError } from "assert";
import { AsyncLocalStorage } from "async_hooks";
import { useAuth } from "content/auth-content";
import * as auth from "./auth-provider";

export const API_URL: string | undefined = process.env.REACT_APP_API_URL;

interface Config extends RequestInit {
  data?: object;
  token?: string;
}

export const http = async (
  endpoint: string,
  { data, token, ...customConfig }: Config = {}
) => {
  const config: RequestInit = {
    method: "GET",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": data ? "application/json" : "",
    },
    ...customConfig,
  };

  if (data) {
    if (config.method?.toUpperCase() === "GET") {
      endpoint += `?${JSON.stringify(data)}`;
    } else {
      config.body = JSON.stringify(data || {});
    }
  }

  return window.fetch(`${API_URL}/${endpoint}`, config).then(async res => {
    if (res.status === 401) {
      await auth.logout();
      window.location.reload();
      return Promise.reject({mes: '请重新登录'});
    }

    const data = await res.json();
    if (res.ok) {
      return data;
    } else {
      Promise.reject(data);
    }
  });
};

/**
 * @description: http hook
 * @return { Promise<any> }
 */
export const useHttp = () => {
  const { user } = useAuth();
  return (...[endpoint, config]: Parameters<typeof http>) => http(endpoint, {
    ...config, token: user?.token
  });
}